<template>
    <page-container>
        <div class="flex property-wrap left-right-wrap">
            <div class="left-wrap">
                <a-cascader
                    v-model:value="projectCodes"
                    :options="treeData"
                    :field-names="{
                        children: 'children',
                        label: 'name',
                        value: 'code',
                    }"
                    placeholder="选择项目名称"
                    style="width: 100%; margin-bottom: 20px"
                    max-tag-count="responsive"
                    @change="handleCascaderChange"
                >
                    <template #displayRender="{ labels, selectedOptions }">
                        <span v-for="(label, index) in labels" :key="selectedOptions[index].value">
                            {{ index + 1 == labels.length ? label : '' }}
                        </span>
                    </template>
                </a-cascader>
                <a-tree v-model:checkedKeys="selectedKeys" checkable :field-names="fieldNames" :tree-data="buildTreeData" @check="buildSelect">
                    <template #title="{ name, id }">
                        <div class="flex justify-between" style="display: flex; align-items: center; justify-content: space-between">
                            <span>{{ name }}</span>
                            <!-- <a-space>
                                <highlight-outlined title="编辑" @click="handleEditBuild(name, id)" />
                                <a-popconfirm title="确定要删除吗 ?" @confirm="handleDeleteBuild(id)">
                                    <delete-outlined title="删除" />
                                </a-popconfirm>
                            </a-space> -->
                        </div>
                    </template>
                </a-tree>
            </div>
            <div class="right-wrap">
                <div class="ant-pro-table">
                    <div class="ant-pro-table-search">
                        <a-form layout="horizontal">
                            <a-row :gutter="16" type="flex" justify="start">
                                <a-col :xs="12" :sm="12" :md="6" :lg="4">
                                    <a-form-item>
                                        <a-input-search placeholder="病区名称" v-model:value="queryParams.deptName" allow-clear enter-button @search="handleSearch()" />
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="24" :sm="24" :md="12" :lg="4">
                                    <a-button @click="handleReset" class="ml-5px">重置</a-button>
                                </a-col>
                            </a-row>
                        </a-form>
                    </div>
                    <a-card :body-style="{ padding: 0 }" ref="elRef">
                        <div class="ant-pro-table-list-toolbar">
                            <div class="ant-pro-table-list-toolbar-container">
                                <div class="ant-pro-table-list-toolbar-left">
                                    <div class="ant-pro-table-list-toolbar-title">病区管理</div>
                                </div>
                                <div class="ant-pro-table-list-toolbar-right">
                                    <a-space align="center">
                                        <a-button type="primary" @click="addDepartment()" v-permission="[`yfwy:caregiver-department:create`]">
                                            <plus-outlined />
                                            新增
                                        </a-button>

                                        <a-button
                                            :disabled="batchList.length == 0"
                                            @click="handleExport()"
                                            :loading="exportLoading"
                                            class="ml-10px"
                                            v-permission="[`yfwy:caregiver-department:export`]"
                                        >
                                            <download-outlined />
                                            批量导出二维码
                                        </a-button>
                                    </a-space>
                                    <div class="ant-pro-table-list-toolbar-divider">
                                        <a-divider type="vertical" />
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip title="刷新">
                                            <reload-outlined @click="reload" />
                                        </a-tooltip>
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip title="密度">
                                            <a-dropdown :trigger="['click']" placement="bottomRight">
                                                <column-height-outlined />
                                                <template #overlay>
                                                    <a-menu
                                                        style="width: 80px"
                                                        :selected-keys="[state.tableSize]"
                                                        @click="
                                                            ({ key }) => {
                                                                fetchDataContext.tableSize = String(key);
                                                            }
                                                        "
                                                    >
                                                        <a-menu-item key="default">
                                                            <a href="javascript:;">默认</a>
                                                        </a-menu-item>
                                                        <a-menu-item key="middle">
                                                            <a href="javascript:;">中等</a>
                                                        </a-menu-item>
                                                        <a-menu-item key="small">
                                                            <a href="javascript:;">紧凑</a>
                                                        </a-menu-item>
                                                    </a-menu>
                                                </template>
                                            </a-dropdown>
                                        </a-tooltip>
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-popover placement="bottomRight" arrowPointAtCenter trigger="click" overlayClassName="ant-pro-table-column-setting-overlay">
                                            <template #title>
                                                <div class="ant-pro-table-column-setting-title">
                                                    <a-checkbox v-model:checked="columnState.checkAll" :indeterminate="columnState.indeterminate" @change="handleColumnAllClick">
                                                        列展示 / 排序
                                                    </a-checkbox>
                                                    <a @click="reset">重置</a>
                                                </div>
                                            </template>
                                            <template #content>
                                                <span class="ant-pro-table-column-setting-list">
                                                    <drag-container
                                                        lockAxis="y"
                                                        dragClass="ant-pro-table-drag-ghost"
                                                        dropClass="ant-pro-table-drop-ghost"
                                                        @drop="({ removedIndex, addedIndex }) => move(removedIndex, addedIndex)"
                                                    >
                                                        <template :key="column.key" v-for="column in dynamicColumnItems">
                                                            <draggable>
                                                                <div class="ant-pro-table-column-setting-list-item">
                                                                    <drag-icon />
                                                                    <a-checkbox :checked="column.checked" @change="handleColumnChange($event, column)">
                                                                        {{ column.label }}
                                                                    </a-checkbox>
                                                                </div>
                                                            </draggable>
                                                        </template>
                                                    </drag-container>
                                                </span>
                                            </template>
                                            <a-tooltip title="列设置">
                                                <setting-outlined />
                                            </a-tooltip>
                                        </a-popover>
                                    </div>
                                    <!-- <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip :title="screenState ? '退出全屏' : '全屏'">
                                            <fullscreen-outlined v-if="!screenState" @click="setFull" />
                                            <fullscreen-exit-outlined v-else @click="exitFull" />
                                        </a-tooltip>
                                    </div> -->
                                </div>
                            </div>
                        </div>
                        <a-table
                            row-key="id"
                            :size="state.tableSize"
                            :loading="state.loading"
                            :columns="dynamicColumns"
                            :data-source="state.dataSource"
                            :pagination="{
                                'show-size-changer': true,
                                current: state.current,
                                pageSize: state.pageSize,
                                total: state.total,
                                showTotal: total => `共 ${total} 条`,
                            }"
                            :scroll="{ x: 1150, y: appStore.tableHeight }"
                            :row-selection="rowSelection"
                            ref="tableRef"
                            :getPopupContainer="_trigger => tableRef.$el"
                            @change="handleTableChange"
                        >
                            <template #bodyCell="{ record, column }">
                                <template v-if="column.dataIndex === 'medicalWaste'">
                                    <span v-if="record.medicalWaste">{{ record.medicalWaste }}</span>
                                    <span v-else>无</span>
                                </template>
                                <template v-if="column.dataIndex === 'collectSign'">
                                    <span v-if="record.collectSign == 1">是</span>
                                    <span v-if="record.collectSign == 0">否</span>
                                </template>
                                <template v-if="column.dataIndex === 'collectRoomNo'">
                                    <span v-if="record.collectRoomNo == 1">是</span>
                                    <span v-if="record.collectRoomNo == 0">否</span>
                                </template>
                                <template v-if="column.dataIndex === 'deliveryPickingSign'">
                                    <span v-if="record.deliveryPickingSign == 1">是</span>
                                    <span v-if="record.deliveryPickingSign == 0">否</span>
                                </template>
                                <template v-if="column.dataIndex === 'deliveryArriveSign'">
                                    <span v-if="record.deliveryArriveSign == 1">是</span>
                                    <span v-if="record.deliveryArriveSign == 0">否</span>
                                </template>
                                <template v-if="column.dataIndex === 'action'">
                                    <a-space>
                                        <a v-permission="[`yfwy:caregiver-department:update`]" @click="editDepartment(record)">编辑</a>
                                        <a v-permission="[`yfwy:caregiver-department:export`]" @click="handleExport(record)">导出二维码</a>
                                        <a-popconfirm title="确定要删除吗 ?" @confirm="onDelete(record)">
                                            <a-button type="text" danger size="small" v-permission="[`yfwy:caregiver-department:delete`]">删除</a-button>
                                        </a-popconfirm>
                                    </a-space>
                                </template>
                            </template>
                        </a-table>
                    </a-card>
                </div>
            </div>
        </div>

        <department :model="departmentModelRef" :visible="departmentVisible" @cancel="handleEditCancel" />
    </page-container>
</template>

<script lang="ts">
    import type { Ref } from 'vue';
    import { defineComponent, reactive, ref, onMounted } from 'vue';
    import {
        PlusOutlined,
        ReloadOutlined,
        ColumnHeightOutlined,
        SettingOutlined,
        DownOutlined,
        FullscreenOutlined,
        FullscreenExitOutlined,
        DeleteOutlined,
        HighlightOutlined,
        DownloadOutlined,
    } from '@ant-design/icons-vue';
    import { Container as DragContainer, Draggable } from '@/components/draggable';
    import { findTree, toTreeArray } from 'xe-utils';
    import { getMedicalProjectTree, getMedicalBuildTree } from '@/api/list/department';
    import { getMedicalBasicDepartmentPage, exportMedicalBasicDepartmentExcel, deleteMedicalBasicDepartment } from '@/api/companion/ward';
    import { deleteBuilding } from '@/api/list/build';
    import type { Pagination, TableColumn } from '@/typing';
    import { useFetchData } from '@/utils/hooks/useFetchData';
    import { useFullscreen } from '@/utils/hooks/useFullscreen';
    import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
    import DragIcon from '@/components/table/drag-icon.vue';
    import Department from './dialog-modal.vue';

    import type { TreeProps, TableProps } from 'ant-design-vue';
    import { message, TableColumnType } from 'ant-design-vue';
    import { isEmpty } from 'lodash-es';
    import { downloadByData } from '@/utils/download';
    import { useAppStore } from '@/store/app';
    const appStore = useAppStore();
    const baseColumns: TableColumn[] = [
        {
            title: '病区名称',
            dataIndex: 'deptName',
        },
        {
            title: '管理人员',
            dataIndex: 'deptCharge',
        },
        {
            title: '管理人员电话',
            dataIndex: 'deptTel',
        },
        {
            title: '操作',
            width: 200,
            dataIndex: 'action',
        },
    ];
    export default defineComponent({
        name: 'InspectionPlan',
        setup() {
            const buildModelRef = ref({});
            const departmentModelRef = ref({});

            const tableRef = ref();
            const {
                state: columnState,
                dynamicColumns,
                dynamicColumnItems,
                handleColumnAllClick,
                handleColumnChange,
                reset,
                move,
            } = useTableDynamicColumns(baseColumns, { needRowIndex: false });
            const queryParams = reactive<any>({
                buildingIds: [],
                projectCode: '',
            });
            const [elRef, screenState, { setFull, exitFull }] = useFullscreen();
            const fetchDataContext = reactive({
                current: 1,
                pageSize: 10,
                tableSize: 'middle', // 'default' | 'middle' | 'small'
                stripe: true,
                isList: false,
                executeImmediately: false,
                requestParams: {
                    ...queryParams,
                },
            });
            const { reload, context: state } = useFetchData(getMedicalBasicDepartmentPage, fetchDataContext);

            const fieldNames: TreeProps['fieldNames'] = {
                children: 'children',
                title: 'name',
                key: 'id',
            };

            const treeData: Ref<TreeProps['treeData']> = ref([]);
            const buildTreeData: Ref<TreeProps['treeData']> = ref([]);

            const projectCodes = ref<string[]>([]);
            const selectedKeys = ref<string[]>([]);
            onMounted(async () => {
                getMedicalProject();
            });
            const getMedicalProject = () => {
                getMedicalProjectTree().then((res: any) => {
                    treeData.value = [res.data as any];

                    const select = findTree([res.data], item => item.type === 'dept' && isEmpty(item.children));
                    projectCodes.value = select.nodes.map(item => item.code);
                    if (select.item.code) {
                        queryParams.projectCode = select.item.code;
                        getMedicalBuildData();
                    } else {
                        message.warning('未查询到项目对应的楼栋信息');
                        buildTreeData.value = [];
                        queryParams.buildingIds = [];
                    }
                });
            };

            const getMedicalBuildData = () => {
                const projectCode = projectCodes.value[projectCodes.value.length - 1];
                queryParams.projectCode = projectCode;

                getMedicalBuildTree(projectCode).then(build => {
                    if (!isEmpty(build.data)) {
                        buildTreeData.value = build.data;

                        selectedKeys.value = [buildTreeData.value[0].id];
                        queryParams.buildingIds = toTreeArray(buildTreeData.value[0].children).map(item => item.id);
                        // selectedKeys.value = queryParams.buildingIds;
                        fetchDataContext.executeImmediately = true;
                        handleSearch();
                    } else {
                        message.warning('未查询到项目对应的楼栋信息');
                        state.dataSource = [];
                        buildTreeData.value = [];
                        queryParams.buildingIds = [];
                    }
                });
            };

            const handleCascaderChange = (value: any, selectedOptions: any) => {
                buildTreeData.value = [];
                batchLists.value = [];
                batchList.value = [];
                queryParams.buildingIds = [];
                const select = selectedOptions[selectedOptions.length - 1];
                if (select.type === 'dept' && select.children.length === 0) {
                    getMedicalBuildData();
                }
            };

            const buildSelect = (selectedKeys: any, e: any) => {
                // if (e.node.children.length == 0 && selectedKeys[0]) {
                //     queryParams.buildingIds = selectedKeys;
                //     handleSearch();
                // }
                selectedKeys.value = selectedKeys;
                queryParams.buildingIds = selectedKeys.value;

                // queryParams.projectCode = projectCodes.value[projectCodes.value.length - 1];
                handleSearch();
            };

            // 表格数据和加载
            const handleTableChange = ({ current, pageSize }: Pagination) => {
                fetchDataContext.current = current;
                fetchDataContext.pageSize = pageSize;
            };

            const handleSearch = () => {
                if (queryParams.buildingIds.length == 0) {
                    state.dataSource = [];
                    return false;
                }
                fetchDataContext.current = 1;
                fetchDataContext.requestParams = { ...queryParams };
            };

            const handleReset = () => {
                Object.keys(queryParams).forEach(key => {
                    if (key != 'projectCode' && key != 'buildingIds') {
                        delete queryParams[key];
                    }
                });
                handleSearch();
            };

            // 批量
            const batchList: any = ref([]);
            const batchLists: any = ref([]);
            const rowSelection: TableProps['rowSelection'] = {
                preserveSelectedRowKeys: true,
                selectedRowKeys: batchLists,
                onChange: (selectedRowKeys: string[], selectedRows: any) => {
                    batchLists.value = selectedRowKeys;
                    batchList.value = selectedRowKeys;
                },
                getCheckboxProps: item => ({
                    disabled: item.inspectionWay == 1,
                }),
            };
            const exportLoading = ref<boolean>(false);
            const handleExport = (record: any) => {
                exportLoading.value = true;
                exportMedicalBasicDepartmentExcel(record ? [record.id] : batchList.value)
                    .then(res => {
                        const temp = res.headers['content-disposition'].split(';')[1].split('filename=')[1];
                        const fileName = decodeURIComponent(temp);

                        downloadByData(res.data, record ? `${record.deptName}病区.zip` : fileName);
                    })
                    .finally(() => {
                        exportLoading.value = false;
                    });
            };

            // 新增修改表单
            const modalVisible = ref<boolean>(false);
            const departmentVisible = ref<boolean>(false);
            const addBuild = () => {
                buildModelRef.value = {
                    projectCode: queryParams.projectCode,
                    projectName: queryParams.projectName,
                };
                modalVisible.value = true;
            };

            const updateModalVisible = ref(false);
            const updateModalRef = reactive<any>({});

            const handleEditBuild = (name: string, key: string) => {
                updateModalRef.name = name;
                updateModalRef.id = key;
                updateModalVisible.value = true;
            };

            const handleDeleteBuild = (key: string) => {
                deleteBuilding(key).then(res => {
                    if (res.data) {
                        message.success('删除成功');
                        getMedicalProject();
                    }
                });
            };

            const addDepartment = () => {
                departmentModelRef.value = {
                    projectCode: queryParams.projectCode,
                    collectSign: 0,
                    collectRoomNo: 0,
                    deliveryPickingSign: 0,
                    deliveryArriveSign: 0,
                };
                departmentVisible.value = true;
            };

            const editDepartment = (record: Record<string, any>) => {
                departmentModelRef.value = { ...record, projectCode: queryParams.projectCode };
                departmentVisible.value = true;
            };

            const onDelete = (data: any) => {
                deleteMedicalBasicDepartment(data.id).then(res => {
                    if (res.code == 200) {
                        message.success('删除成功');
                        reload();
                    }
                });
            };

            const handleEditCancel = () => {
                modalVisible.value = false;
                departmentVisible.value = false;
                reload();
            };

            return {
                getMedicalProject,
                handleDeleteBuild,
                updateModalVisible,
                updateModalRef,
                addDepartment,
                editDepartment,
                handleCascaderChange,
                projectCodes,
                buildTreeData,
                addBuild,
                handleEditBuild,
                departmentVisible,
                departmentModelRef,
                selectedKeys,
                appStore,
                exportLoading,
                handleExport,
                buildSelect,
                tableRef,
                fieldNames,
                treeData,
                handleSearch,
                queryParams,
                reload,
                state,
                columnState,
                dynamicColumns,
                dynamicColumnItems,
                // fullscreen
                elRef,
                screenState,
                setFull,
                exitFull,
                handleTableChange,
                handleColumnChange,
                handleColumnAllClick,
                reset,
                move,
                onDelete,
                handleEditCancel,
                // 表单
                modalVisible,

                buildModelRef,
                fetchDataContext,
                handleReset,
                rowSelection,
                batchList,
            };
        },
        components: {
            DragIcon,
            PlusOutlined,
            ReloadOutlined,
            ColumnHeightOutlined,
            SettingOutlined,
            FullscreenOutlined,
            FullscreenExitOutlined,
            Draggable,
            DownOutlined,
            DragContainer,
            Department,
            DeleteOutlined,
            HighlightOutlined,
            DownloadOutlined,
        },
    });
</script>
